﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

using BBICMS.Model;
using System.Data.Entity.Infrastructure;
using BBICMS.Core;

namespace BBICMS.Repository
{
    public abstract class EFRepository<T> : IEFRepository<T> where T : BaseEntity
    {
        protected DbContext Context;
        protected readonly IDbSet<T> DbSet;

        protected EFRepository(DbContext context)
        {
            Context = context;
            DbSet = context.Set<T>();
        }

        public virtual IEnumerable<T> GetAll()
        {

            return DbSet.AsEnumerable<T>();
        }


        public IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            var query = DbSet.Where(predicate).AsEnumerable();
            return query;
        }

        public virtual T GetById(int id)
        {
            return this.DbSet.Find(id);
        }
        public virtual void Add(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);
            if (entry.State != EntityState.Detached)
            {
                entry.State = EntityState.Added;
            }
            else
            {
                this.DbSet.Add(entity);
            }
        }
        public virtual void Update(T entity)
        {
            DbEntityEntry entry = Context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                DbSet.Attach(entity);
            }

            entry.State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);

            if (entry.State != EntityState.Deleted)
            {
                entry.State = EntityState.Deleted;
            }
            else
            {
                this.DbSet.Attach(entity);
                this.DbSet.Remove(entity);
            }
        }

        public virtual void Delete(int id)
        {
            var entity = this.GetById(id);

            if (entity != null)
            {
                this.Delete(entity);
            }
        }


        public virtual void Save()
        {
            Context.SaveChanges();
        }
    }
}
